package com.qingmu.club.minaapi.custom.logic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Component
public class ClubUsersLogic {
    
    @Autowired
    ClubUsersService ClubUsersService;

    @Autowired
    ClubService clubService;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    UsersService usersService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubUsersIntegralService clubUsersIntegralService;

    @Autowired
    IntegralAttentionPresentService integralAttentionPresentService;

    @Autowired
    ClubUsersCourseService clubUsersCourseService;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseClasshourService courseClasshourService;

    @Autowired
    ClubUsersClasshoursService clubUsersClasshoursService;

    /**
     * 查询门店粉丝
     * @param shopId
     * @return
     */
    public int queryUserSum(String shopId){
        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.SHOP_ID,shopId).eq(ClubUsers.ATTENTION_STATUS,1); //已关注;
        return this.ClubUsersService.count(queryWrapper);
    }


    /**
     * 查询用户关注的门店列表
     * @param userId
     * @return
     */
    public List<ClubShop> queryUserAttentionShop(String userId){
        QueryWrapper<Club> clubQueryWrapper = new QueryWrapper<>();
        clubQueryWrapper.eq(Club.STATUS,0);
        List<Club> clubList = this.clubService.list(clubQueryWrapper);
        String[] clubIds = new String[clubList.size()];
        for(int i=0 ;i<clubIds.length;i++){
            clubIds[i]=clubList.get(i).getId();
        }

        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(ClubUsers.USER_ID,userId)
                .orderByDesc(ClubUsers.CREATE_TIME)
                .eq(ClubUsers.ATTENTION_STATUS,1); //已关注
        if(clubIds.length!=0){
            queryWrapper.notIn(ClubShop.CLUB_ID,clubIds);
        }
        List<ClubUsers> ClubUserss = this.ClubUsersService.list(queryWrapper);

        List<ClubShop> clubUserShopList = new ArrayList<>();
        for(ClubUsers ClubUsers:ClubUserss){
            ClubShop clubShop = this.clubShopService.getById(ClubUsers.getShopId());
            if(clubShop.getStatus()==0){
                continue;
            }
            clubUserShopList.add(clubShop);
        }
        return clubUserShopList;
    }

    /**
     * 查询用户是否关注该门店
     * @param shopId
     * @param userId
     * @return
     */
    public ClubUsers getUserShop(String shopId, String userId){
        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.SHOP_ID,shopId).eq(ClubUsers.USER_ID,userId).eq(ClubUsers.ATTENTION_STATUS,1);
        List<ClubUsers> shopClubUserss = this.ClubUsersService.list(queryWrapper);
        if(CollectionUtils.isEmpty(shopClubUserss)){
            return null;
        }
        return shopClubUserss.get(0);
    }


    /**
     * 查询用户关注的俱乐部
     * @param userId
     * @return
     */
    public Club userClubUsersNew(String userId){
        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.USER_ID,userId).orderByDesc(ClubUsers.CREATE_TIME);
        List<ClubUsers> shopClubUserss = this.ClubUsersService.list(queryWrapper);
        if(CollectionUtils.isEmpty(shopClubUserss)){
            return null;
        }
        ClubUsers attention = shopClubUserss.get(0);
        ClubShop clubShop= this.clubShopService.getById(attention.getShopId());

        return this.clubService.getById(clubShop.getClubId());
    }

    /**
     * 魔力拼团核销成功之后，会员自动关注该魔力拼团所属门店，让其能够在B端显示
     * @param userId
     * @param shopId
     * @return
     */

    public void autoAttentionShop (String userId, String shopId){

        Users users = this.usersService.getById(userId);

        ClubShop clubShop = this.clubShopService.getById(shopId);

        //判断该会员，有没有关注过该门店，没有则核销拼团时自动关注门店
        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.USER_ID, userId)
                .eq(ClubUsers.SHOP_ID, shopId);
        ClubUsers clubUsers = this.ClubUsersService.getOne(queryWrapper);

        //如果用户已绑定该门店，则默认关注该门店
        if (clubUsers != null){
            clubUsers.setAttentionStatus(KeyValueDefine.ATTENTION_SHOP);
            this.clubUsersService.updateById(clubUsers);
        }

        //如果用户还未绑定该门店，则新绑定该门店
        else if (clubUsers == null) {

            //查询门店积分规则，给会员添加相应的关注门店积分
            QueryWrapper<IntegralAttentionPresent> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3
                    .eq(IntegralAttentionPresent.CLUB_ID, clubShop.getClubId())
                    .eq(IntegralAttentionPresent.STATUS, KeyValueDefine.ONLINE_STATUS);
            IntegralAttentionPresent attentionPresent = this.integralAttentionPresentService.getOne(queryWrapper3);
            Integer userJf = 0;
            if (attentionPresent != null) {
                userJf = attentionPresent.getPresentIntegral();
            }

            Integer attentionStatus = 1;//魔力拼团成功默认关注门店

            ClubUsers newClubUsers = new ClubUsers();
            newClubUsers.setUserId(users.getId());
            newClubUsers.setUserName(users.getUserName());
            newClubUsers.setUserSex(users.getUserSex());
            newClubUsers.setClubId(clubShop.getClubId());
            newClubUsers.setShopId(shopId);
            newClubUsers.setShopName(clubShop.getShopName());
            newClubUsers.setShopAvater(clubShop.getCover1());
            newClubUsers.setAttentionTime(new Date());
            newClubUsers.setAttentionStatus(attentionStatus);
            newClubUsers.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
            newClubUsers.setUserIcon(users.getUserIcon());
            newClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
            newClubUsers.setAttentionType(KeyValueDefine.ATTENTION_SHOP);
            newClubUsers.setUserJf(userJf);
            newClubUsers.setUserMobile(users.getUserMobile());
            this.clubUsersService.save(newClubUsers);

            ClubUsersIntegral clubUsersIntegral = new ClubUsersIntegral();
            clubUsersIntegral.setIntegralName("关注积分");
            clubUsersIntegral.setClubUsersId(newClubUsers.getId());
            clubUsersIntegral.setUserId(userId);
            clubUsersIntegral.setShopId(shopId);
            clubUsersIntegral.setIntegralNum(userJf);//关注积分
            clubUsersIntegral.setType(KeyValueDefine.JF_ADD);//积分增加
            clubUsersIntegral.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
            clubUsersIntegral.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
            clubUsersIntegral.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享关注得积分
            this.clubUsersIntegralService.save(clubUsersIntegral);

        }

    }


    /**
     * 魔力拼团核销成功，给会员绑定拼团对应的课程
     * @param staffId
     * @param userId
     * @param shopId
     * @param courseId
     * @return
     */
    public void autoSetClubUsersCourse ( String staffId, String userId, String shopId, String courseId) {


        //反查用户的clubUsersId，作为判断用户是否已经绑定该课程的条件
        ClubUsers clubUsers = this.clubUsersService.getOne(new QueryWrapper<ClubUsers>()
                .lambda()
                .eq(ClubUsers::getUserId, userId)
                .eq(ClubUsers::getShopId, shopId)
                .last("limit 1")
        );

        //如果有已读课程 那么将已读改成历史课程
        QueryWrapper<ClubUsersCourse> onlineCourse = new QueryWrapper<>();
        onlineCourse.lambda().eq(ClubUsersCourse::getType, 0).eq(ClubUsersCourse::getClubUsersId, clubUsers.getId());
        ClubUsersCourse usersCourse = this.clubUsersCourseService.getOne(onlineCourse);
        if (usersCourse != null) {
            usersCourse.setType(1);//历史课程
            this.clubUsersCourseService.updateById(usersCourse);

        }

        Course course = this.courseService.getById(courseId);
        //会员绑定课程
        ClubUsersCourse clubUsersCourse = new ClubUsersCourse();
        clubUsersCourse.setCourseId(courseId);
        clubUsersCourse.setClubUsersId(clubUsers.getId());
        clubUsersCourse.setUserName(clubUsers.getUserName());
        clubUsersCourse.setStatus(1);//0-已完成的课程 1-正在学习的课程
        clubUsersCourse.setCourseName(course.getCourseName());
        clubUsersCourse.setCreateUser(staffId);
        clubUsersCourse.setType(0); //0-在读课程 1-历史课程
        this.clubUsersCourseService.save(clubUsersCourse);


        //修改用户信息
        clubUsers.setSumHours(course.getQuantity());//冗余
        clubUsers.setRemainHours(course.getQuantity());
        clubUsers.setBuyCourseId(courseId);
        clubUsers.setBuyCourseName(course.getCourseName());
        clubUsers.setAttendShop(course.getShopId());
        clubUsers.setAttendShopName(course.getShopName());
        clubUsers.setUserShowStatus("online");  //在读人员
//        clubUsers.setUserJf(clubUsers.getUserJf() + course.getIntegral());//客户说魔力拼团绑定课程不需要再次送积分
        this.clubUsersService.updateById(clubUsers);


        //课程课时列表
        QueryWrapper<CourseClasshour> classhourQueryWrapper = new QueryWrapper<>();
        classhourQueryWrapper.lambda().eq(CourseClasshour::getCourseId, courseId);
        List<CourseClasshour> classhours = this.courseClasshourService.list(classhourQueryWrapper);

        //给会员绑定拼团对应的课时
        List<ClubUsersClasshours> addHoursList = new ArrayList<>();
        for (CourseClasshour classhour : classhours) {
            ClubUsersClasshours usersClasshours = new ClubUsersClasshours();
            usersClasshours.setClasshourId(classhour.getId());
            usersClasshours.setClasshourName(classhour.getClasshourName());
            usersClasshours.setCourseId(classhour.getCourseId());
            usersClasshours.setClubUsersId(clubUsers.getId());
            usersClasshours.setStatus(0);
            if (!StringUtils.isEmpty(clubUsers.getAttendCoach()))
                usersClasshours.setAttendCoach(clubUsers.getAttendCoach());
            if (!StringUtils.isEmpty(clubUsers.getAttendCoachName()))
                usersClasshours.setAttendCoachName(clubUsers.getAttendCoachName());
            addHoursList.add(usersClasshours);
        }
        this.clubUsersClasshoursService.saveBatch(addHoursList);


        //需求方说通过魔力拼团购买的课程不需要送课程所对应的积分
//        //添加绑定课程的用户积分记录
//        ClubUsersIntegral clubUsersIntegral = new ClubUsersIntegral();
//        clubUsersIntegral.setClubUsersId(clubUsers.getId());
//        clubUsersIntegral.setUserId(clubUsers.getUserId());
//        clubUsersIntegral.setShopId(clubUsers.getShopId());
//        clubUsersIntegral.setIntegralName(course.getCourseName());
//        clubUsersIntegral.setType(1);//增加
//        clubUsersIntegral.setIntegralNum(course.getIntegral());
//        clubUsersIntegral.setClubUsersName(clubUsers.getUserName());
//        clubUsersIntegral.setIntegralType(1);
//        clubUsersIntegral.setGoodsImage(course.getCourseImage());
//        this.clubUsersIntegralService.save(clubUsersIntegral);

    }


}
